#!/bin/bash

set -e

USER_FILE=${ROOT_DIR}/text/user.md

function user_exist_check() {
    set +e
    $(id -u $1 >/dev/null 2>&1)
    if [[ $? -eq 0 ]]; then
        return 1
    else
        return 0
    fi
}

function add_users() {
    if [ ! -f ${USER_FILE} ]; then
        echo -e "Please set list file dir"
        return 0
    fi

    while read install_cmd; do
        local cnt=$(echo "${install_cmd}" | grep -c ":")
        if [[ ${cnt} -eq 0 ]]; then
            continue
        fi
        echo -e "cmd is ${install_cmd}"
        local user_name=$(echo -e "${install_cmd}" | awk -F : '{print $1}')
        local user_passwd=$(echo -e "${install_cmd}" | awk -F : '{print $2}')
        local user_bash=$(echo -e "${install_cmd}" | awk -F : '{print $NF}')
        user_exist_check ${user_name}
        if [[ $? -ne 0 ]]; then
            echo "${user_name} is exist"
            continue
        fi
        set -e
        echo -e "user_name is ${user_name}, user_passwd is ${user_passwd}, bash is ${user_bash}"
        bash -c "useradd -d /home/${user_name} -s ${user_bash} -r -m ${user_name}"
        echo "create user success"
        bash -c "echo ${user_name}:${user_passwd} | chpasswd"
        echo -e "set password success"
    done < ${USER_FILE}
}

add_users
